package BookLibrary;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

public class BookDB
{

    public List<Book> getBookFromDB() {
        List<Book> toReturn = new LinkedList<Book>();
        try {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "56264034");
                ps = conn.prepareStatement("Select * from library.books");
                rs = ps.executeQuery();
                Book bk = null;
                while (rs.next()) {
                    bk = new Book(rs.getInt("id"), rs.getString("name"), rs.getString("author_id"));
                    toReturn.add(bk);
                }
            }
            finally{
                if(conn != null){
                    conn.close();
                    conn = null;
                }
                if(ps != null){
                    ps.close();
                    ps = null;
                }
                if(rs != null){
                    rs.close();
                    rs = null;
                }
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return toReturn;

    }
}
